# @rspress/plugin-twoslash <SourceCode href="https://github.com/web-infra-dev/rspress/tree/main/packages/plugin-twoslash" />

import { SourceCode, PackageManagerTabs, Tabs, Tab } from '@theme';

Integration of [Twoslash](https://github.com/twoslashes/twoslash)'s Rspress Plugin for automatically generating rich code blocks with type information.

## Installation

<PackageManagerTabs command="add @rspress/plugin-twoslash -D" />

## Usage

### 1. Register the plugin

```ts twoslash title="rspress.config.ts"
import { defineConfig } from '@rspress/core';
import { pluginTwoslash } from '@rspress/plugin-twoslash';

export default defineConfig({
  plugins: [pluginTwoslash()],
});
```

### 2. Write code blocks with twoslash

Use special comments within TypeScript code blocks to enable Twoslash features.

For more detailed usage, please refer to the [Twoslash documentation](https://twoslash.netlify.app/guide/).

#### Extract type

<Tabs>
<Tab label="Rendered">

```ts twoslash
const hi = 'Hello';
const msg = `${hi}, world`;
//    ^?
```

</Tab>
<Tab label="Syntax">

````mdx
```ts twoslash
const hi = 'Hello';
const msg = `${hi}, world`;
//    ^?
```
````

</Tab>
</Tabs>

#### Completions

<Tabs>
<Tab label="Rendered">

```ts twoslash
// @noErrors
console.e;
//       ^|
```

</Tab>
<Tab label="Syntax">

````mdx
```ts twoslash
// @noErrors
console.e;
//       ^|
```
````

</Tab>
</Tabs>

#### Highlighting

<Tabs>
<Tab label="Rendered">

```ts twoslash
function add(a: number, b: number) {
  //     ^^^
  return a + b;
}
```

</Tab>
<Tab label="Syntax">

````mdx
```ts twoslash
function add(a: number, b: number) {
  //     ^^^
  return a + b;
}
```
````

</Tab>
</Tabs>

#### Error

<Tabs>
<Tab label="Rendered">

```ts twoslash
// @noErrorValidation
const str: string = 1;
```

</Tab>
<Tab label="Syntax">

````mdx
```ts twoslash
// @noErrorValidation
const str: string = 1;
```
````

</Tab>
</Tabs>

## Config

The plugin accepts an object with the following type:

```ts twoslash
import { TwoslashOptions } from 'twoslash';
// ---cut-before---
export interface PluginTwoslashOptions {
  explicitTrigger?: boolean;
  cache?: boolean;
  twoslashOptions?: TwoslashOptions;
}
```

### explicitTrigger

`explicitTrigger` is used to configure whether to explicitly trigger the Twoslash feature. Default is `true`.

- If set to `false`, all TypeScript code blocks will be processed by default.
- If set to `true`, only code blocks with the `twoslash` tag will be processed.

### cache

`cache` is used to cache the TypeScript language servers based on compiler options when calling [createTwoslasher](https://twoslash.netlify.app/refs/api#createtwoslasher). Default is `true`.

### twoslashOptions

`twoslashOptions` is used to pass options to Twoslash.
This allows you to customize the Twoslash behavior, including TypeScript compiler options and other settings.
